//
//  AppDelegate.m
//  penzer
//
//  Created by caiyc on 2018/9/18.
//  Copyright © 2018年 caiyc. All rights reserved.
//   

#import "AppDelegate.h"
#import "HostHomeViewController.h"
#import <IDLFaceSDK/FaceSDKManager.h>
#import "WXApi.h"
#import "LiveViewController.h"
#import "LoginViewController.h"
#import "HomeViewController.h"
#import "Host_IndexViewController.h"
//#import "BIndexViewController.h"
#import <BDCloudAVLicense/BDCloudAVAuthentication.h>
#import <BDCloudMediaPlayer/BDCloudMediaPlayer.h>
#import "WebViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "SJTabBarController.h"
#import "SPNewVersionView.h"
#import "ComenLoginViewController.h"
#import "HostablityViewController.h"
#import "SocailViewController.h"
#import "Host_Detail_Ablum_ViewController.h"
#import "GHSTabBarController.h"

static NSString * const kAccessKey = @"8643cf93d7fa4cf7897b10a7191ca73d";//8643cf93d7fa4cf7897b10a7191ca73d    //36a33862f54f47029ea0a3caedef3b3a
static NSString * const kSecretKey = @"7289921dd22e45139865d9374131c8d1";
static NSString * const kUserId = @"aa53433ed94c41cea1f3bb7168791006";
static NSString *const WeixinAppid = @"wx130fbddb55a30f80";


@interface AppDelegate ()<BDCloudMediaPlayerAuthDelegate,WXApiDelegate,CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager *locationManager;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //初始化页面
    [self load];
    //百度云播放器认证 （App启动后，必须进行认证，否则播放器无法运行。）
    [self BDCMediaPlayerAuth];
    //位置使用授权
    [self.locationManager requestAlwaysAuthorization];
    //开启定位
    [self.locationManager startUpdatingLocation];
    //初始化人脸识别
    [self faceManager];
    //微信相关注册
    [WXApi registerApp:WeixinAppid];
    //新版本升级检测
    //[SPNewVersionView check];
    
    // 列表/页面偏移 进行全局设置
    if (@available(iOS 11.0, *)){
      //  [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
    return YES;
}



#pragma mark--初始化页面
-(void)load
{
    if([XTool GetDefaultInfo:Prole]){
        //有登陆的状态
        NSInteger role = [[XTool GetDefaultInfo:Prole] integerValue];
        [self changeRootWithRoleType:role];
        
    }else{
        //没登录任何账号的状态
       // LoginViewController *vc = [[LoginViewController alloc]init];
        ComenLoginViewController *vc = [[ComenLoginViewController alloc] initWithRoleType:RoleType_YH];
        CPNavigation *nav = [[CPNavigation alloc] initWithRootViewController:vc];
        [nav setNavigationBarHidden:1];
        self.window.rootViewController =nav;
    }
}



#pragma mark--去登录
- (void)goComenLoginWithRoleType:(RoleType)roleType targetVc:(UIViewController *)vc
{
    ComenLoginViewController *login = [[ComenLoginViewController alloc]initWithRoleType:roleType];
    //    [self.navigationController pushViewController:vc animated:YES];
    CPNavigation *nav = [[CPNavigation alloc] initWithRootViewController:login];
    [vc presentViewController:nav animated:YES completion:nil];
}


#pragma mark--百度云播放器认证
- (void)BDCMediaPlayerAuth
{
    [BDCloudMediaPlayerAuth sharedInstance].delegate = self;
    [[BDCloudMediaPlayerAuth sharedInstance] setAccessKey:kAccessKey];
    
    // 用户认证信息
    BDCloudAVAuthCredential *credential = [[BDCloudAVAuthCredential alloc] init];
    credential.userId = kUserId;
    credential.accessKey = kAccessKey;
    credential.secretKey = kSecretKey;

    // AK/SK方式鉴权
    [BDCloudAVAuthentication authenticateWithCredential:credential completionHandler:^(NSError *error) {
        if (error) {
            NSLog(@"--->AK/SK方式鉴权失败：%@",error);
        }else{
            NSLog(@"--->AK/SK方式鉴权成功");
        }
    }];
   
}



#pragma mark--BDCloudMediaPlayerAuthDelegate
- (void)authStart {
    RZLog(@"---->百度云播放器认证开始");
}

- (void)authEnd:(NSError*)error {
    // 认证完成，error为空表示认证成功。
    if(!error){
        RZLog(@"---->百度云播放器认证成功");
    }else{
       RZLog(@"---->百度云播放器认证失败--%@",error);
    }
}


#pragma mark--人脸识别
- (void)faceManager
{
    NSString *licensePath = [[NSBundle mainBundle]pathForResource:FACE_LICENSE_NAME ofType:FACE_LICENSE_SUFFIX];
    [[FaceSDKManager sharedInstance]setLicenseID:FACE_LICENSE_ID andLocalLicenceFile:licensePath];
    NSLog(@"canwork=%d",[[FaceSDKManager sharedInstance]canWork]);
}


#pragma mark--切换身份
-(void)changeRootWithRoleType:(RoleType)roleType
{
    switch (roleType) {
        case RoleType_YH:{//用户
            HomeViewController *rootVc = [[HomeViewController alloc]init];
            CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:rootVc];
            [nav setNavigationBarHidden:1];
            self.window.rootViewController = nav;
            break;
        }
            
        case RoleType_ZB:{//主播
            Host_IndexViewController*rootVc = [[Host_IndexViewController alloc]init];
            //  LiveViewController *rootVc = [[LiveViewController alloc]init];
            CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:rootVc];
            [nav setNavigationBarHidden:1];
            self.window.rootViewController = nav;
            break;
        }
            
        case RoleType_SJ:{//商家
            self.window.rootViewController = [SJTabBarController new];
            break;
        }
            
        case RoleType_GHS:{//供货商
            self.window.rootViewController = [GHSTabBarController new];
            break;
        }
    }
}



#pragma mark--CLLocationManagerDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:locations[0] completionHandler:^(NSArray *array, NSError *error){
        if(array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //获取城市
            NSString *city = placemark.locality;
            if(!city) {
                //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                city = placemark.administrativeArea;
            }
            [XTool SaveDefaultInfo:city Key:LOCATION];
            
        }else if(error == nil && [array count] == 0){
            NSLog(@"No results were returned.");
        }else if(error != nil){
            NSLog(@"An error occurred = %@", error);
        }
        
    }];
    [manager stopUpdatingLocation];
}




// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    return [WXApi handleOpenURL:url delegate:self];
}



#pragma mark--微信支付回调
-(void)onResp:(BaseResp*)resp{
    if ([resp isKindOfClass:[PayResp class]]){
        PayResp*response=(PayResp*)resp;
        switch(response.errCode){
            case WXSuccess:{//服务器端查询支付通知或查询API返回的结果再提示成功
                NSDictionary *resultDic = @{@"resultStatus":@"9000"};
                NSDictionary *dic = @{@"payResult":resultDic,@"payType":@"weixin"};
                [[NSNotificationCenter defaultCenter]postNotificationName:@"paynoti" object:nil userInfo:dic];
                [WToast showWithText:@"支付成功"];
                NSLog(@"支付成功");
                break;
            }
                
            default:{
                NSDictionary *resultDic = @{@"resultStatus":@"6001"};
                NSDictionary *dic = @{@"payResult":resultDic};
                [[NSNotificationCenter defaultCenter]postNotificationName:@"paynoti" object:nil userInfo:dic];
                NSLog(@"支付失败，retcode=%d",resp.errCode);
                break;
            }
                
        }
    }
}




- (void)applicationWillResignActive:(UIApplication *)application
{
    NSDictionary *dic = @{@"status":@"nocollect"};
    [[NSNotificationCenter defaultCenter]postNotificationName:@"enterback" object:dic];
}


- (void)applicationDidEnterBackground:(UIApplication *)application
{
    //进入后台模式
    [[NSNotificationCenter defaultCenter]postNotificationName:@"enterback" object:nil];;
}


- (void)applicationWillEnterForeground:(UIApplication *)application
{
     [[NSNotificationCenter defaultCenter]postNotificationName:@"enterback" object:nil];;
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    //重新唤醒
    [[NSNotificationCenter defaultCenter]postNotificationName:@"enterforhead" object:nil];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


#pragma mark--审核阶段
- (void)alternative
{
    //审核阶段
    //    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    //     NSString *url = @"http://dev.sharepanzer.com/api/bzapi.php?i=10&c=entry&ctrl=live_anchor&ac=store&op=activity&m=bz_activities&token=8175f62516aae4aa5e9ff6fc81b44112&ta=pian";
    //    [manager POST:url parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
    //        SLog(@"请求结果：%@",responseObject);
    //        if([responseObject[@"message"][@"data"]integerValue]==1){
    //            WebViewController *we = [[WebViewController alloc]init];
    //            self.window.rootViewController  = we;
    //        }else{
    //
    //            [self load];
    //            [self location];
    //        }
    //
    //    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
    //        SLog(@"请求出错===……%@",error);
    //    }];
    
    // Override point for customization after application launch.
    //    HostHomeViewController *rootVc = [[HostHomeViewController alloc]init];
    //    CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:rootVc];
    //    [nav setNavigationBarHidden:1];
    //
    //    HomeViewController *rootVc = [[HomeViewController alloc]init];
    //    CPNavigation *nav = [[CPNavigation alloc]initWithRootViewController:rootVc];
    //    [nav setNavigationBarHidden:1];
    //
    //    self.window.rootViewController = nav;
    
    // 用户认证信息
//        BDCloudAVAuthCredential *credential = [[BDCloudAVAuthCredential alloc] init];
    //    credential.userId = kUserId;
    //    credential.accessKey = kAccessKey;
    //    credential.secretKey = kSecretKey;
    
    //    [[BDCloudMediaPlayerAuth sharedInstance] setAccessKey:kAccessKey];
    //    // AK/SK方式鉴权
    //    // 鉴权成功，error为nil
    //    // 鉴权失败，返回相应的error信息
    ////    [BDCloudAVAuthentication authenticateWithCredential:credential completionHandler:^(NSError *error) {
    ////        if (error) {
    ////            NSLog(@"authenticate error, %@",error);
    ////        }
    ////    }];
}


#pragma mark--getter&&setter
- (CLLocationManager *)locationManager
{
    if(!_locationManager){
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        // 设置定位精确度到米
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 设置过滤器为无
        _locationManager.distanceFilter = kCLDistanceFilterNone;
    }
    return _locationManager;
}
@end
